package com.angola.sms.base

import android.Manifest
import android.annotation.SuppressLint
import android.app.role.RoleManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.telecom.TelecomManager
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.annotations.AfterPermissionGranted
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog
import com.angola.sms.component.dialog.LoadingDialogipetrpide
import com.angola.sms.component.dialog.MessageDialog
import com.angola.sms.extipetrpide.canHideKeyboardipetrpide
import com.angola.sms.extipetrpide.hideKeyboardipetrpide
import com.angola.sms.extipetrpide.setFullScreenMode
import com.angola.sms.network.NetworkException


const val REQ_CODE_PAGE_PERMISSION: Int = 200
const val REQ_CODE_PAGE_UNKNOW_SOURCES = 10087
const val REQ_CODE_ROLE_DIALER = 10088
const val DEF_REQ_CODE_PAGE_PERMISSION: Int = 200
const val DEF_BUNDLE_KEY_CONTENT = "DEF_BUNDLE_KEY_CONTENT"


abstract class BaseActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    var ACTIVITY_TAG: String = ""

    private lateinit var mLoadingDialogipetrpide: LoadingDialogipetrpide
    private var mPermissionListipetrpide: Array<String>? = null
    private var mPermissionStatementipetrpide: String? = null
    private var mSavedInstanceState: Bundle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ACTIVITY_TAG = this::class.java.simpleName
        mSavedInstanceState = savedInstanceState

        with(window) {
//            requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
//            exitTransition = Slide(Gravity.START).setDuration(300)
//            enterTransition = Slide(Gravity.END).setDuration(300)
//            exitTransition = Fade()
//            enterTransition = Slide()
        }
        //mFirebaseAnalytics = Firebase.analytics
        setFullScreenMode()
        ACTIVITY_TAG = onBindingViewTag()
        setContentView(onBindingContentView())
//        setContentView(onBindingContentLayoutId())
        mLoadingDialogipetrpide = LoadingDialogipetrpide(this)
        setViewModelActionsipetrpide()
        onContentViewBinded()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null) {
                try {
                    if (canHideKeyboardipetrpide(view, ev)) {
                        hideKeyboardipetrpide()
                        val editText = view as EditText
                        editText.clearFocus()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    override fun onResume() {
        super.onResume()
//        val gTypeipetrpide = "${this.javaClass.simpleName}_START".uppercase()
//        RepoTool.saveUserBuriedPointipetrpide(ToSaveUserBuriedPointTo(gTypeipetrpide))
    }

    override fun onPause() {
        super.onPause()
//        val gTypeipetrpide = "${this.javaClass.simpleName}_END".uppercase()
//        RepoTool.saveUserBuriedPointipetrpide(ToSaveUserBuriedPointTo(gTypeipetrpide))
    }

    /**绑定model*/
    protected abstract fun onBindingViewModel(): List<ViewModel>?

    /**绑定tag*/
    protected abstract fun onBindingViewTag(): String

    /**绑定视图开始*/
    protected abstract fun onBindingContentView(): View

    /**绑定视图开始*/
//    protected abstract fun onBindingContentLayoutId(): Int

    /**绑定视图完成*/
    protected abstract fun onContentViewBinded()

    private fun setViewModelActionsipetrpide() {
        val viewModelListipetrpide = onBindingViewModel()
        if (!(viewModelListipetrpide.isNullOrEmpty())) {
            viewModelListipetrpide.forEach {
                if (it is IBaseViewModelAction) {
                    it.getLoadingLiveDataipetrpide().observe(this) { showLoading ->
                        if (showLoading)
                            showLodingDialogipetrpide()
                        else
                            dismissLoadingDialogipetrpide()
                    }

                    it.getNetworkExceptionLiveDataipetrpide().observe(this) {
                        onHandleNetworkExceptonipetrpide(it)
                    }
                }
            }
        }
    }

    protected fun showLodingDialogipetrpide() {
        mLoadingDialogipetrpide.showDialogipetrpide(this)
    }

    protected fun dismissLoadingDialogipetrpide() {
        mLoadingDialogipetrpide.dismissDialogipetrpide()
    }

    /**交给子类去实现*/
    open fun onHandleNetworkExceptonipetrpide(networkExceptionipetrpide: NetworkException) {
        if (networkExceptionipetrpide.isAlteripetrpide()) {
            MessageDialog.showDialogipetrpide(supportFragmentManager, networkExceptionipetrpide.msg)
        } else {
            Toast.makeText(this, networkExceptionipetrpide.msg, Toast.LENGTH_LONG)
                .show()
        }
    }

    /**交给子类去实现*/
    open fun onPermissionsRequestAllPassipetrpide() {

    }

    /**交给子类去实现*/
    open fun onDialerRoleRequestAllPass() {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        mPermissionStatementipetrpide?.let {
            mPermissionListipetrpide?.let { list ->
                startEasyPermissionsipetrpide(it, list)
            }
        }
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            mPermissionStatementipetrpide?.let {
                mPermissionListipetrpide?.let { list ->
                    startEasyPermissionsipetrpide(it, list)
                }
            }
        } else if (requestCode == REQ_CODE_PAGE_UNKNOW_SOURCES) {
            requestLaunchPermissionsipetrpide()

        } else if (requestCode == REQ_CODE_ROLE_DIALER) {
            println("请求替换默认电话器返回")
            onDialerRoleRequestAllPass()
        }
    }

    @AfterPermissionGranted(REQ_CODE_PAGE_PERMISSION)
    fun onEasyPermissionsAllPassipetrpide() {
        onPermissionsRequestAllPassipetrpide()
    }

    open fun requestLaunchPermissionsipetrpide() {
        try {
            //如果是已登录且权限未同意，保存日志
//            if (UserStateHelpipetrpide.isDidLogin()) {
//                埋点事件 Re-request permission
//                val notAgreePerListipetrpide = getNotAgreeLaunchPermissions()
//                if (notAgreePerListipetrpide.isNotEmpty()) {
//                    val notAgreeListStringipetrpide = notAgreePerListipetrpide.joinToString(",")
//                    val gTypeipetrpide = "RE_REQUEST_PERMISSION".uppercase()
//                    val gRemarkipetrpide =
//                        "${this.javaClass.simpleName}#${notAgreeListStringipetrpide}".uppercase()
//                    RepoTool.saveUserBuriedPointipetrpide(
//                        ToSaveUserBuriedPointTo(
//                            gTypeipetrpide,
//                            gRemarkipetrpide
//                        )
//                    )
//                }
//            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                startEasyPermissionsipetrpide(
                    "App requires some permissions",
                    arrayOf(
                        Manifest.permission.READ_SMS,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_CONTACTS
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_PHONE_STATE,
//                        Manifest.permission.CALL_PHONE,
//                        Manifest.permission.READ_PHONE_NUMBERS,
//                        Manifest.permission.PROCESS_OUTGOING_CALLS
                    )
                )
            } else {
                startEasyPermissionsipetrpide(
                    "App requires some permissions",
                    arrayOf(
                        Manifest.permission.READ_SMS,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_CONTACTS
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_PHONE_STATE,
//                        Manifest.permission.CALL_PHONE,
//                        Manifest.permission.READ_PHONE_NUMBERS,
//                        Manifest.permission.PROCESS_OUTGOING_CALLS
                    )
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    protected fun startEasyPermissionsipetrpide(
        reqStatementipetrpide: String,
        permissionListipetrpide: Array<String>
    ) {
        mPermissionStatementipetrpide = reqStatementipetrpide
        mPermissionListipetrpide = permissionListipetrpide

        EasyPermissions.requestPermissions(
            this,
            reqStatementipetrpide,
            REQ_CODE_PAGE_PERMISSION,
            *permissionListipetrpide
        )
    }

    fun getNeedPermissions() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            if (packageManager.canRequestPackageInstalls()) {
//                requestLaunchPermissionsipetrpide()
//            } else {
//                requestUnknowAppPage()
//            }
//        } else {
//            requestLaunchPermissionsipetrpide()
//        }
        requestLaunchPermissionsipetrpide()
    }

    fun requestUnknowAppPage() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                intent.data = Uri.parse("package:$packageName")
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivityForResult(
                    intent,
                    REQ_CODE_PAGE_UNKNOW_SOURCES
                )
            } else {
                requestLaunchPermissionsipetrpide()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @SuppressLint("WrongConstant")
    @RequiresApi(Build.VERSION_CODES.Q)
    fun requstDefaultDialer() {
        val roleManagerService = getSystemService(Context.ROLE_SERVICE)
        if (roleManagerService != null) {
            val roleManager = roleManagerService as RoleManager
            val valid = roleManager.isRoleAvailable(RoleManager.ROLE_DIALER)
            println("valid $valid")
            val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER)
            startActivityForResult(
                intent,
                REQ_CODE_ROLE_DIALER
            )
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                println("Android M 以上的系统则发起将本应用设为默认电话应用的请求")
                val intent = Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER)
                intent.putExtra(
                    TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
                    packageName
                )
                startActivity(intent)
                onDialerRoleRequestAllPass()
            } else {
                onDialerRoleRequestAllPass()
            }
        }
    }
}